import { useEffect, useState, useRef } from "react";
import ProForm, {
  ProFormText,
  ProFormSelect,
  ProFormDigit,
  ProFormList,
  ProFormDependency,
} from "@ant-design/pro-form";
import ProCard from "@ant-design/pro-card";
import { message } from "antd";
import { LeftOutlined } from "@ant-design/icons";

import UploadFile from "@/components/UploadFile";
import { packageTypeOptions } from "@/const";
import EditableLabels from "@/components/EditableLabels";
import { add, update, fetchInfo } from "@/api/package";
import { PageContainer, FooterToolbar } from "@ant-design/pro-layout";
import { useLocation, history } from "umi";
import { fetchMallBookList } from "@/api/book";
import Editor from "@/components/Editor";

export default () => {
  const location = useLocation();
  const { id } = location.query;
  const title = id ? "编辑书包" : "新增书包";
  const formRef = useRef();

  const getInfo = async () => {
    const res = await fetchInfo({ id });
    if (res.code == 200) {
      const postData = {
        ...res.data,
        images: res.data.images?.map((item) => ({ url: item })),
        readGuide: res.data.readGuide?.map((item) => ({ name: item })),
        normalLabel: res.data.normalLabel?.map((item) => ({ name: item })),
        themeLabel: res.data.themeLabel?.map((item) => ({ name: item })),
      };
      console.log("postData===", postData);
      formRef.current.setFieldsValue(postData);
    }
  };

  useEffect(() => {
    if (id) {
      getInfo();
    }
  }, []);

  const handleAddOrUpdate = async (fields) => {
    const postData = {
      ...fields,
      id: id,
      images: fields.images?.map((item) => item.url),
      readGuide: fields.readGuide?.map((item) => item.name),
      normalLabel: fields.normalLabel?.map((item) => item.name),
      themeLabel: fields.themeLabel?.map((item) => item.name),
    };
    let func = add;
    if (id) {
      func = update;
    }
    const res = await func(postData);
    if (res.code == 200) {
      message.success(title + "成功");
      history.goBack();
    }
  };

  return (
    <PageContainer
      header={{
        title: (
          <div className="pointer" onClick={() => history.goBack()}>
            <LeftOutlined style={{ marginRight: 10 }} />
            {title}
          </div>
        ),
        breadcrumb: {},
      }}
    >
      <ProForm
        layout="horizontal"
        formRef={formRef}
        labelCol={{
          span: 2,
        }}
        onFinish={async (values) => {
          return handleAddOrUpdate(values);
        }}
        submitter={{
          render: (_, dom) => <FooterToolbar>{dom}</FooterToolbar>,
        }}
        initialValues={{
          cycle: 12,
          specification: 10,
        }}
      >
        <ProCard title="基础信息" bordered>
          <ProFormSelect
            width="lg"
            name="type"
            label="类型"
            allowClear
            fieldProps={{
              options: packageTypeOptions,
            }}
            rules={[{ required: true, message: "请选择类型" }]}
          />
          <ProFormText
            width="lg"
            label="名称"
            name="name"
            rules={[
              { required: true, message: "请输入名称" },
              {
                max: 50,
                message: "最长为50位",
              },
            ]}
          />
          <ProFormDigit
            width="lg"
            label="数量"
            name="specification"
            placeholder="请输入数量"
            min={1}
            max={99999999}
            addonAfter="本书/期"
            fieldProps={{
              precision: 0,
            }}
            rules={[{ required: true, message: "请输入数量" }]}
          />

          <ProFormDigit
            width="lg"
            label="售卖价"
            name="sellPrice"
            placeholder="请输入售卖价"
            min={1}
            max={99999999}
            addonAfter="元"
            fieldProps={{
              precision: 2,
            }}
            rules={[{ required: true, message: "请输入售卖价" }]}
          />
          <ProFormDigit
            width="lg"
            label="支付价格"
            name="payPrice"
            placeholder="请输入支付价格"
            min={1}
            max={99999999}
            addonAfter="元"
            fieldProps={{
              precision: 2,
            }}
            rules={[{ required: true, message: "请输入支付价格" }]}
          />

          <ProFormDigit
            disabled
            width="lg"
            label="周期"
            name="cycle"
            placeholder="请输入周期"
            min={1}
            addonAfter="期"
            fieldProps={{
              precision: 0,
              // onChange: (e) => {
              //   const arr = Array.from({ length: e }, (_, i) => {
              //     return { phaseNum: i + 1, phaseBooks: [] };
              //   });
              //   formRef.current.setFieldValue("phases", arr);
              // },
            }}
            rules={[{ required: true, message: "请输入周期" }]}
          />

          <ProForm.Item
            name="images"
            label="图片"
            tooltip="建议尺寸：750*750"
            rules={[{ required: true, message: "请上传图片" }]}
          >
            <UploadFile maxCount={9} />
          </ProForm.Item>
        </ProCard>
        <ProCard style={{ marginTop: 20 }} title="主题标签" bordered>
          <ProFormList
            name="themeLabel"
            rules={[
              {
                required: true,
                validator: async (_, value) => {
                  if (value && value.length > 0) {
                    return;
                  }
                  throw new Error("至少要有一项！");
                },
              },
            ]}
            copyIconProps={false}
            max={4}
            creatorButtonProps={{
              style: { width: 440 },
              creatorButtonText: "新增",
            }}
          >
            <ProFormText
              key="name"
              name="name"
              width="lg"
              rules={[
                { required: true, message: "请输入" },
                {
                  max: 100,
                  message: "最长为100位",
                },
              ]}
            />
          </ProFormList>
        </ProCard>

        <ProCard
          style={{ marginTop: 20 }}
          title="培育阅读素养与写作能力"
          bordered
        >
          <ProFormList
            name="readGuide"
            copyIconProps={false}
            max={10}
            creatorButtonProps={{
              style: { width: 440 },
              creatorButtonText: "新增",
            }}
          >
            <ProFormText
              key="name"
              name="name"
              width="lg"
              rules={[
                { required: true, message: "请输入" },
                {
                  max: 100,
                  message: "最长为100位",
                },
              ]}
            />
          </ProFormList>
        </ProCard>

        <ProCard
          style={{ marginTop: 20 }}
          title="阅读赋能韧性与抗逆力提升"
          bordered
        >
          <ProFormList
            name="normalLabel"
            copyIconProps={false}
            max={100}
            creatorButtonProps={{
              style: { width: 440 },
              creatorButtonText: "新增",
            }}
          >
            <ProFormText
              key="name"
              name="name"
              width="lg"
              rules={[
                { required: true, message: "请输入" },
                {
                  max: 100,
                  message: "最长为100位",
                },
              ]}
            />
          </ProFormList>
        </ProCard>

        <ProCard style={{ marginTop: 20 }} title="详情" bordered>
          <ProForm.Item
            name="content"
            rules={[{ required: true, message: "请输入详情" }]}
          >
            <Editor />
          </ProForm.Item>
        </ProCard>
      </ProForm>
    </PageContainer>
  );
};
